package com.ht.module.bus.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.constant.BusConstant;
import com.ht.module.bus.entity.*;
import com.ht.module.bus.mapper.*;
import com.ht.module.bus.service.TClassService;
import com.ht.module.bus.service.TDistrictService;
import com.ht.module.bus.service.TSchoolService;
import com.ht.module.bus.service.TStudentService;
import com.ht.module.bus.vo.CompanyAnnualTripRankingVo;
import com.ht.module.bus.vo.StudentNumberRankingVo;
import com.ht.module.sys.entity.SysDict;
import com.ht.module.sys.entity.SysDictItem;
import com.ht.module.sys.service.ISysDictService;
import com.ht.util.CommMethod;
import com.ht.util.JsonResult;
import com.ht.util.Pager;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 统计分析
 * </p>
 *
 * @author hejialun
 * @since 2024-08-23
 */
@RestController
@RequestMapping("/statistics")
public class StatisticsController {
    @Resource
    private ISysDictService sysDictService;
    @Resource
    private TSchoolMapper schoolMapper;
    @Resource
    private TStudentMapper studentMapper;
    @Resource
    private TTransportationCompanyStatisticsMapper transportationCompanyStatisticsMapper;
    @Resource
    private TDistrictMapper districtMapper;
    @Resource
    private TDistrictService districtService;
    @Resource
    private TStudentTripStatisticsMapper studentTripStatisticsMapper;


    @ApiOperation("按学校维度分析")
    @GetMapping("/schoolDimension")
    public JsonResult schoolDimension() {
        List<SysDictItem> dicts = sysDictService.getItem("education_level");
        Map<String, Long> map = new HashMap<>();
        List<TSchool> list = schoolMapper.selectList(
                new QueryWrapper<TSchool>()
        );

        for (SysDictItem item : dicts) {
            long count = list.stream().filter(x -> StrUtil.equals(x.getEducationStateName(), item.getValue())).count();
            map.put(item.getLabel(), count);
        }
        return JsonResult.success(map);
    }


    @ApiOperation("按学生维度分析")
    @GetMapping("/studentDimension")
    public JsonResult studentDimension() {
        List<SysDictItem> dicts = sysDictService.getItem("education_stage");
        Map<String, Long> map = new HashMap<>();
        List<TStudent> list = studentMapper.findListAuth(
                new QueryWrapper<TStudent>()
                        .eq("del_flag", BusConstant.DEL_FLAG_N),
                null
        );
        for (SysDictItem item : dicts) {
            long count = list.stream().filter(x -> StrUtil.equals(x.getEducationStage(), item.getValue())).count();
            map.put(item.getLabel(), count);
        }
        return JsonResult.success(map);
    }


    @ApiOperation("按运输企业维度分析")
    @GetMapping("/companyDimension")
    public JsonResult companyDimension() {
        //查询出所有区划
        List<TDistrict> districts = districtMapper.selectList(
                new QueryWrapper<TDistrict>()
        );
        //查询出所有企业统计数据
        List<TTransportationCompanyStatistics> list = transportationCompanyStatisticsMapper.selectList(
                new QueryWrapper<TTransportationCompanyStatistics>()
        );

        //查询出所有学生数据
        List<TStudent> students = studentMapper.findListAuth(
                new QueryWrapper<TStudent>()
                        .eq("del_flag", BusConstant.DEL_FLAG_N),
                null
        );
        List<Map<String, Object>> data = new ArrayList<>();
        for (TDistrict district : districts) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("districtCode", district.getDistrictCode());
            map.put("districtName", district.getDistrictName());
            //设置区划学生出行需求
            map.put("studentNum", students.stream().filter(x -> StrUtil.equals(x.getStationdistrictCode(), district.getDistrictCode())).count());
            //设置企业数量
            map.put("companyNum", list.stream().filter(x -> StrUtil.equals(x.getDistrictCode(), district.getDistrictCode())).count());
            //设置运输车辆数
            map.put("carNum",
                    list.stream().filter(x -> StrUtil.equals(x.getDistrictCode(), district.getDistrictCode()))
                            .mapToInt(TTransportationCompanyStatistics::getCarNumber)
                            .sum()
            );
            //护苗专线全年趟次
            map.put("runNum",
                    list.stream().filter(x -> StrUtil.equals(x.getDistrictCode(), district.getDistrictCode()))
                            .map(x -> x.getRunNumber() * x.getCarNumber())
                            .mapToInt(Integer::intValue)
                            .sum()
            );

            data.add(map);
        }
        return JsonResult.success(data);
    }


    @ApiOperation("运送学生数量排名")
    @GetMapping("/studentNumberRanking")
    public JsonResult studentNumberRanking(TStudentTripStatistics en) {
        QueryWrapper<TStudentTripStatistics> qw = new QueryWrapper<>();
        qw.eq("del_flag", BusConstant.DEL_FLAG_N);
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            qw.in("district_code", sonList);
        }
        //查询所有学生运输数据
        List<TStudentTripStatistics> list = studentTripStatisticsMapper.findListAuth(qw, null);
        //按学校编码分组
        Map<String, List<TStudentTripStatistics>> groupMap = list.stream().filter(x -> StrUtil.isNotEmpty(x.getSchoolCode())).collect(Collectors.groupingBy(TStudentTripStatistics::getSchoolCode));

        //定义返回的map
        List<StudentNumberRankingVo> retList = new ArrayList<>();

        for (String key : groupMap.keySet()) {
            StudentNumberRankingVo vo = new StudentNumberRankingVo();
            //当前学校的集合
            List<TStudentTripStatistics> temps = groupMap.get(key);
            int sum = temps.stream().map(TStudentTripStatistics::getWantNumber)
                    .mapToInt(Integer::intValue)
                    .sum();
            //获取当前学生
            TStudentTripStatistics row = list.stream().filter(x -> StrUtil.equals(x.getSchoolCode(), key)).findFirst().orElse(null);

            if (row != null) {
                vo.setNum(sum);
                vo.setSchoolName(row.getSchoolName());
                vo.setSchoolCode(key);
                retList.add(vo);
            }
        }
        return JsonResult.success(
                //降序排序
                retList.stream()
                        .sorted(Comparator.comparingLong(StudentNumberRankingVo::getNum).reversed())
                        .collect(Collectors.toList())
        );
    }

    @ApiOperation("运输企业全年趟次排名")
    @GetMapping("/companyAnnualTripRanking")
    public JsonResult companyAnnualTripRanking(TTransportationCompanyStatistics en) {
        QueryWrapper<TTransportationCompanyStatistics> qw = new QueryWrapper<TTransportationCompanyStatistics>()
                .eq("year", LocalDate.now().getYear())
                .eq("del_flag", BusConstant.DEL_FLAG_N);
        //查询条件
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            qw.in("district_code", sonList);
        }
        List<TTransportationCompanyStatistics> list = transportationCompanyStatisticsMapper.findListAuth(qw, null);
        //按企业分组
        Map<String, List<TTransportationCompanyStatistics>> groupMap = list
                .stream().filter(x -> StrUtil.isNotEmpty(x.getCompanyCode()))
                .collect(Collectors.groupingBy(TTransportationCompanyStatistics::getCompanyCode));

        //定义返回集合
        List<CompanyAnnualTripRankingVo> retList = new ArrayList<>();

        for (String key : groupMap.keySet()) {
            CompanyAnnualTripRankingVo vo = new CompanyAnnualTripRankingVo();

            List<TTransportationCompanyStatistics> temps = groupMap.get(key);

            //获取全年趟次
            int num = temps.stream().map(TTransportationCompanyStatistics::getRunNumber)
                    .mapToInt(Integer::intValue)
                    .sum();
            //获取当前企业
            TTransportationCompanyStatistics row = list.stream().filter(x -> StrUtil.equals(x.getCompanyCode(), key)).findFirst().orElse(null);

            if (row != null) {
                vo.setNum(num);
                vo.setCompanyName(row.getCompanyName());
                vo.setCompanyCode(key);
                retList.add(vo);
            }
        }

        return JsonResult.success(
                //降序排序
                retList.stream()
                        .sorted(Comparator.comparingLong(CompanyAnnualTripRankingVo::getNum).reversed())
                        .collect(Collectors.toList())
        );
    }

    @ApiOperation("运输企业全年座次排名")
    @GetMapping("/companyAnnualOrderSeatsRanking")
    public JsonResult companyAnnualOrderSeatsRanking(TTransportationCompanyStatistics en) {
        QueryWrapper<TTransportationCompanyStatistics> qw = new QueryWrapper<TTransportationCompanyStatistics>()
                .eq("year", LocalDate.now().getYear())
                .eq("del_flag", BusConstant.DEL_FLAG_N);
        //查询条件
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            qw.in("district_code", sonList);
        }
        List<TTransportationCompanyStatistics> list = transportationCompanyStatisticsMapper.findListAuth(qw, null);
        //按企业分组
        Map<String, List<TTransportationCompanyStatistics>> groupMap = list
                .stream().filter(x -> StrUtil.isNotEmpty(x.getCompanyCode()))
                .collect(Collectors.groupingBy(TTransportationCompanyStatistics::getCompanyCode));

        //定义返回集合
        List<CompanyAnnualTripRankingVo> retList = new ArrayList<>();

        for (String key : groupMap.keySet()) {
            CompanyAnnualTripRankingVo vo = new CompanyAnnualTripRankingVo();

            List<TTransportationCompanyStatistics> temps = groupMap.get(key);

            //获取全年趟次
            int num = temps.stream().map(x -> {
                        return x.getRunNumber() * x.getCarNumber() * x.getSeatNumber();
                    })
                    .mapToInt(Integer::intValue)
                    .sum();
            //获取当前企业
            TTransportationCompanyStatistics row = list.stream().filter(x -> StrUtil.equals(x.getCompanyCode(), key)).findFirst().orElse(null);

            if (row != null) {
                vo.setNum(num);
                vo.setCompanyName(row.getCompanyName());
                vo.setCompanyCode(key);
                retList.add(vo);
            }
        }

        return JsonResult.success(
                //降序排序
                retList.stream()
                        .sorted(Comparator.comparingLong(CompanyAnnualTripRankingVo::getNum).reversed())
                        .collect(Collectors.toList())
        );
    }


    @ApiOperation("需运输学生比例按教育阶段统计")
    @GetMapping("/studentTransportScale")
    public JsonResult studentTransportScale(TStudentTripStatistics en) {
        List<SysDictItem> dicts = sysDictService.getItem("education_stage");
        Map<String, BigDecimal> map = new HashMap<>();
        QueryWrapper<TStudentTripStatistics> qw = new QueryWrapper<TStudentTripStatistics>()
                .eq("del_flag", BusConstant.DEL_FLAG_N);
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            qw.in("district_code", sonList);
        }
        List<TStudentTripStatistics> list = studentTripStatisticsMapper.findListAuth(qw, null);
        for (SysDictItem item : dicts) {
            long wantNumber = list.stream()
                    .filter(x -> StrUtil.equals(x.getEducationStage(), item.getValue()))
                    .map(TStudentTripStatistics::getWantNumber)
                    .mapToInt(Integer::intValue)
                    .sum();

            long countNum = list.stream()
                    .filter(x -> StrUtil.equals(x.getEducationStage(), item.getValue()))
                    .map(x -> x.getWantNumber() + x.getNoWantNumber())
                    .mapToInt(Integer::intValue)
                    .sum();
            if (countNum == 0) {
                map.put(item.getLabel(), new BigDecimal(0));
            } else {
                map.put(item.getLabel(), new BigDecimal(wantNumber).divide(new BigDecimal(countNum), 2, RoundingMode.HALF_UP));
            }

        }
        return JsonResult.success(map);


    }


    @ApiOperation("全县参与运输学校比例")
    @GetMapping("/schoolTransportScale")
    public JsonResult schoolTransportScale(TStudentTripStatistics en) {
        List<SysDictItem> dicts = sysDictService.getItem("education_level");
        Map<String, BigDecimal> map = new HashMap<>();
        QueryWrapper<TStudentTripStatistics> qw = new QueryWrapper<TStudentTripStatistics>()
                .eq("del_flag", BusConstant.DEL_FLAG_N);
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            qw.in("district_code", sonList);
        }
        List<TStudentTripStatistics> list = studentTripStatisticsMapper.findListAuth(qw, null);
        //查询出所有学校
        QueryWrapper<TSchool> schoolQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            List<String> sonList = districtService.getSonList(en.getDistrictCode());
            sonList.add(en.getDistrictCode());
            schoolQueryWrapper.in("district_code",sonList);
        }

        List<TSchool> allList = schoolMapper.selectList(schoolQueryWrapper);
        for (SysDictItem item : dicts) {
            //按学校类型分组
            Map<String, List<TStudentTripStatistics>> groupMap = list.stream().filter(x -> StrUtil.isNotEmpty(x.getEducationStateName()))
                    .collect(Collectors.groupingBy(TStudentTripStatistics::getEducationStateName));

            //获取当前类型学校总数
            long count = allList.stream().filter(x -> StrUtil.equals(x.getEducationStateName(), item.getValue())).count();
            if (count == 0) {
                map.put(item.getLabel(), new BigDecimal(0));
                continue;
            }
            List<TStudentTripStatistics> temps = groupMap.get(item.getValue());
            if (BeanUtil.isEmpty(temps)) {
                map.put(item.getLabel(), new BigDecimal(0));
                continue;
            }
            //如果存在数据。按学校编码去重
            long num = temps.stream().map(TStudentTripStatistics::getSchoolCode)
                    .filter(new HashSet<>()::add) // 使用 Set 的 add 方法确保唯一性
                    .count();


            map.put(item.getLabel(),
                    new BigDecimal(num).divide(new BigDecimal(count), 2, RoundingMode.HALF_UP)
            );
        }
        return JsonResult.success(map);
    }
}
